﻿using Peninsula.Common.Log;
using Peninsula.Site.Data.Constant;
using Peninsula.Site.Data.Result;
using Peninsula.Utility.Extensions;
using System;

namespace Peninsula.Site.Data.Result
{
    public static class OperateResultExtensions
    {

        public static ILogger Logger { set; private get; }

        public static void SetCodeMsg<T>(this OperateResult<T> operateResult, int code)
        {
            operateResult.Code = code;
            operateResult.Msg = ErrorCodes.CodeMsgDict[code];
        }


        public static OperateResult<T> RunWithTry<T>(this OperateResult<T> operateResult, Action<OperateResult<T>> runMethod)
        {
            try
            {
                operateResult.SetCodeMsg(ErrorCodes.OK);
                runMethod.Invoke(operateResult);
            }
            catch (Exception ex)
            {
                operateResult.SetCodeMsg(ErrorCodes.SERVER_ERROR);
                operateResult.Msg = ex.Message;
                Logger.LogException($"RunWithTry Error, {System.Web.HttpContext.Current.Request.Url.AbsolutePath}", ex);
            }
            return operateResult;
        }
    }
}
